package com.company.netty2;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;

/**
 * @description: DelimiterBasedFrameDecoder 客户端类
 * @author: ruoan
 * @date: 2021/1/1 17:24
 */
public class EchoClientHandlerWithDecoder extends ChannelInboundHandlerAdapter {


    private int counter;
    private static final String ECHO_REQ = "Hi, Mr.Bruce,welcome to Netty's world.$_";

    public EchoClientHandlerWithDecoder() {
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 10; i++) {
            ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes()));
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("这是第"+ ++counter +"次收到消息【"+msg+"】");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
        System.out.println("关闭");
    }
}
